<template>
  <view class="lottery">
    <view class="lottery-grid">
      <view class="box-ly-zp" :style="style_box">
        <view :animation="animationData" class="cs-ct" :style="style_wh">
          <view class="cs-line">
            <view
              class="cs-litem"
              v-for="(item, index) in awardsList"
              :key="index"
              :style="[
                { transform: 'rotate(' + item.lineTurn + ')' },
                { 'background-color': themeColor },
                { left: width / 2 + 'rpx' },
                { height: height / 2 + 'rpx' },
                { '-webkit-transform-origin': '50% ' + height / 2 + 'rpx' },
                { 'transform-origin': '50% ' + height / 2 + 'rpx' }
              ]"
            ></view>
          </view>
          <view class="cs-list">
            <view class="cs-item" :style="{ color: viewColor }" v-for="(iteml, index2) in awardsList" :key="index2">
              <view
                class="cs-item-text"
                :style="[
                  { transform: 'rotate(' + iteml.turn + ')' },
                  { '-webkit-transform-origin': '50% ' + height / 2 + 'rpx' },
                  { 'transform-origin': '50% ' + height / 2 + 'rpx' }
                ]"
              >
                <text class="txt">{{ iteml.name }}</text>
                <!-- <image lazy-load="true" class="cs-item-text-img" :src="iteml.img" @tap="toDetailPage({index: index2})"></image> -->
              </view>
            </view>
          </view>
        </view>
        <view
          @tap="playReward"
          class="cs-btn"
          :style="[{ left: width / 2 - 40 + 'rpx' }, { top: height / 2 - 40 + 'rpx' }]"
          v-bind:class="btnDisabled"
        >
          开始
        </view>
        <view
          class="cs-btn-table"
          :style="[{ left: width / 2 - 60 + 'rpx' }, { top: height / 2 + 50 + 'rpx' }, { color: viewColor }]"
        >
          剩余{{ num }}次
        </view>
      </view>
    </view>

    <view class="grid">
      <button class="btn-green" @click="refresh">刷新次数</button>
      <button class="btn-blue" @click="toRecord">抽奖记录</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      list_r: [],
      roleId: null,
      num: 0,
      height: 600,
      width: 600,
      chance: true,
      themeColor: '#33CCCC',
      stay_index: 0,
      viewColor: '#6739b6',
      awardsList: {},
      animationData: {},
      btnDisabled: ''
    }
  },
  async onLoad() {},
  async onShow() {
    let that = this
    that.roleId = this.vuex_user.id
    that.getCofig()
  },
  computed: {
    style_box() {
      let that = this
      var height = parseInt(that.height)
      var width = parseInt(that.width)
      var style = ''
      if (height > 0) {
        style = `height:${height}rpx;`
      }
      if (width > 0) {
        style += `width:${width}rpx;`
      }
      style += `border: 8rpx solid ${that.themeColor};`
      return style
    },
    style_wh() {
      let that = this
      var height = parseInt(that.height)
      var width = parseInt(that.width)
      var style = ''
      if (height > 0) {
        style = `height:${height}rpx;`
      }
      if (width > 0) {
        style += `width:${width}rpx;`
      }
      return style
    }
  },
  methods: {
    /**
     * 点击抽奖后回调
     *
     * @param {Object} e
     */
    async resultFun_chance(e) {
      let that = this
      let item = e.item

      if (e.isAward) {
        this.msg_modal('获得 [' + item.name + '] 元', '恭喜中奖')
      }
    },
    /**
     * 抽奖提示框
     */
    msg_modal(content, title = '温馨提示') {
      //统一提示方便全局修改
      if (Boolean(content) === false) {
        return
      }
      uni.showModal({
        title: title,
        content: content,
        confirmText: '确定',
        showCancel: false,
        confirmColor: '#33CCCC',
        success(res) {
          if (res.confirm) {
          }
        }
      })
    },
    /**
     * 获取抽奖配置项
     */
    async getCofig() {
      uni.showLoading({
        title: '加载抽奖配置中',
        mask: true
      })

      let res = await this.$u.api.getLuckdrawConfig()
      let data = JSON.parse(JSON.stringify(res))
      this.list_r = []
      data.forEach((item, index) => {
        let param = {
          index: index,
          name: item.amt,
          isAward: true,
          val: 1,
          type: 1,
          img: ''
        }

        this.list_r.push(param)
      })

      // 加载抽奖页面
      this.init()

      // 获取可抽奖次数
      let params = {
        roleId: this.roleId
      }
      let num = await this.$u.api.getLuckdrawNum(params)
      this.num = num

      uni.hideLoading()
    },
    /**
     * 跳转抽奖记录页面
     */
    toRecord() {
      this.$u.route({
        type: 'navigateTo',
        url: '/pages/index/luckdraw/luckdraw_record'
      })
    },
    /**
     * 刷新抽奖次数
     */
    async refresh() {
      // 获取可抽奖次数
      let params = {
        roleId: this.roleId
      }
      let num = await this.$u.api.getLuckdrawNum(params)
      this.num = num

      this.$u.toast('刷新完成')
    },
    /**
     * 详情页
     *
     * @param {Object} item
     */
    toDetailPage(item) {
      let that = this
      let list = that.awardsList
      let index = item.index
      let data = {
        curIndex: index,
        item: list[index],
        list: list
      }
      this.$emit('toDetailPage', data)
    },
    /**
     * 画抽奖圆盘
     */
    init() {
      var awards = this.list_r
      var awardsList = []
      var turnNum = (1 / awards.length) * 360 // 文字旋转 turn 值

      // 奖项列表
      for (var i = 0; i < awards.length; i++) {
        awardsList.push({
          turn: i * turnNum + 'deg',
          lineTurn: i * turnNum + turnNum / 2 + 'deg',
          name: awards[i].name,
          img: awards[i].img
        })
      }

      this.btnDisabled = this.chance ? '' : 'disabled'
      this.awardsList = awardsList
    },
    /**
     * 发起抽奖
     */
    async playReward() {
      let that = this

      if (this.num == 0) {
        uni.showToast({
          title: '次数已经用完',
          icon: 'none'
        })
        return
      }

      // 开始抽奖 放入中奖下标
      var awardIndex = that.stay_index
      const res = await this.$u.api.luckdraw()
      that.list_r.forEach((item, index) => {
        if (item.name == res) {
          // 放入中奖位置
          awardIndex = index
        }
      })

      //中奖index
      var awardsNum = that.list_r
      //var awardIndex = Math.round(Math.random() * (awardsNum.length - 1)); //随机数
      var runNum = 8 //旋转8周
      var duration = 4000 //时长

      // 旋转角度
      this.runDeg = this.runDeg || 0
      this.runDeg = this.runDeg + (360 - (this.runDeg % 360)) + (360 * runNum - awardIndex * (360 / awardsNum.length))
      //创建动画
      var animationRun = uni.createAnimation({
        duration: duration,
        timingFunction: 'ease'
      })
      animationRun.rotate(that.runDeg).step()
      that.animationData = animationRun.export()
      that.btnDisabled = 'disabled'

      // 中奖提示
      var isAward = that.list_r[awardIndex].isAward || false
      that.num = that.num - 1
      if (isAward) {
        setTimeout(
          function () {
            that.btnDisabled = ''
          }.bind(that),
          duration
        )
      } else {
        setTimeout(
          function () {
            uni.showModal({
              title: '很遗憾',
              content: '没中 ' + that.list_r[awardIndex].name,
              showCancel: false
            })
            that.btnDisabled = ''
          }.bind(that),
          duration
        )
      }

      setTimeout(
        function () {
          let data = {
            curIndex: awardIndex,
            item: that.list_r[awardIndex],
            list: that.list_r,
            isAward: isAward
          }
          this.resultFun_chance(data)
        }.bind(that),
        duration
      )
    }
  }
}
</script>

<style lang="scss">
.lottery {
  width: 100vw;
  height: 100vh;
  display: flex;
  padding-top: 200rpx;
  text-align: center;
  align-items: center;
  flex-direction: column;
  background-size: 100% 100%;
}

.lottery-grid {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  text-align: center;
  flex-direction: column;
  margin-top: 160rpx;
}

.grid {
  margin-top: 100rpx;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: center;
}

.selected {
  background-color: #8dc63f;
}

.btn-green {
  display: flex;
  justify-content: flex-end;
  margin-right: 10px;
  padding: 10px 20px;
  font-size: 16px;
  border-radius: 10px;
  border: none;
  background-color: #39b54a;
  color: #fff;
  cursor: pointer;
}

.btn-blue {
  display: flex;
  justify-content: flex-start;
  margin-left: 10px;
  padding: 10px 20px;
  font-size: 16px;
  border-radius: 10px;
  border: none;
  background-color: #0081ff;
  color: #fff;
  cursor: pointer;
}

// 以下都是抽奖css
.txt {
  padding-top: 60upx;
  padding-bottom: 10upx;
}

/* 转盘 */
.box-ly-zp {
  margin: 0 auto;
  position: relative;
  border-radius: 50%;
  box-shadow: 0 10upx 30upx #333, 0 0 10upx #000;
}

.cs-ct {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 1;
  display: block;
  border-radius: inherit;
  background-clip: padding-box;
}

.cs-element {
  position: relative;
  z-index: 1;
  width: inherit;
  height: inherit;
  border-radius: 50%;
}

.cs-list {
  position: absolute;
  left: 0;
  top: 0;
  width: inherit;
  height: inherit;
  z-index: 9999;
}

.cs-item {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  font-weight: bold;
  text-shadow: 0 1upx 1upx rgba(255, 255, 255, 0.6);
}

.cs-item-text {
  position: relative;
  display: block;
  padding-top: 20upx;
  margin: 0 auto;
  text-align: center;

  display: flex;
  flex-direction: column;
  align-items: center;
}

.cs-item-text text {
  font-size: 40upx;
}

.cs-item-text-img {
  width: 60upx;
  height: 60upx;

  border-radius: 50%;
}

/* 分隔线 */
.cs-line {
  position: absolute;
  left: 0;
  top: 0;
  width: inherit;
  height: inherit;
  z-index: 99;
}

.cs-litem {
  position: absolute;

  top: 0;
  width: 3upx;

  overflow: hidden;
}

/**  
	* 抽奖按钮  
	*/
.cs-btn {
  position: absolute;
  background-color: #e44025;
  z-index: 400;
  width: 80upx;
  height: 80upx;
  border-radius: 50%;
  color: #f4e9cc;
  line-height: 80upx;
  text-align: center;
  font-size: 26upx;
  text-shadow: 0 -1px 1px rgba(0, 0, 0, 0.6);
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.6);
  text-decoration: none;
}

.cs-btn::after {
  position: absolute;
  display: block;
  content: ' ';
  left: 12upx;
  top: -44upx;
  width: 0;
  height: 0;
  overflow: hidden;
  border-width: 30upx;
  border-style: solid;
  border-color: transparent;
  border-bottom-color: #e44025;
}

.cs-btn.disabled {
  pointer-events: none;
  background: #b07a7b;
  color: #ccc;
}

.cs-btn.disabled::after {
  border-bottom-color: #b07a7b;
}

.cs-btn-table {
  width: 120upx;
  text-align: center;
  position: absolute;

  font-size: 26upx;
  background-color: #ffffff;
  opacity: 0.9;
}
</style>
